package com.shaoshaohuo.app.adapter;

import java.text.ParseException;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap.Config;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.EcCartItem;
import com.shaoshaohuo.app.framework.log.LogUtil;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.fragment.EcCartFragment;
import com.shaoshaohuo.app.view.ProgressDialog;
import com.shaoshaohuo.app.utils.NumberUtil;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.ToastUtil;

public class CartAdapter extends MyBaseAdapter<EcCartItem> implements OnClickListener {
//	private static HashMap<Integer, Boolean> isSelected = new HashMap<Integer, Boolean>();
	private ViewHolder holder;
	private EcCartFragment cartFragment;
	protected int touchedPosition;
	private ProgressDialog progressDialog;
	private static EditText newPurchaseQuantity;

	public CartAdapter(Context ctx, EcCartFragment cartFragment, List<EcCartItem> list, boolean flag) {
		super(ctx, list, flag);
		this.cartFragment = cartFragment;
		progressDialog = new ProgressDialog(ctx);;
	}

	@Override
	public void setData(List<EcCartItem> lst) {
		super.setData(lst);
	}
//
//	public static HashMap<Integer, Boolean> getIsSelected() {
//		return isSelected;
//	}
//
//	public static void setIsSelected(HashMap<Integer, Boolean> isSelected) {
//		CartAdapter.isSelected = isSelected;
//	}

	@Override
	public View getView(int pos, View convertView, ViewGroup group) {
		final int index = pos;
		if (convertView == null) {
			convertView = View.inflate(context, R.layout.fragment_cart_list_item, null);
			holder = new ViewHolder();
			holder.cbSelectItem = (CheckBox) convertView.findViewById(R.id.checkbox_ec_cart_single_select);
			holder.supplierName = (TextView) convertView.findViewById(R.id.supplier_name);
			holder.supplierAddress = (TextView) convertView.findViewById(R.id.supplier_address);
			holder.imageEcCartItem = (ImageView) convertView.findViewById(R.id.image_ec_cart_item);
			holder.productName = (TextView) convertView.findViewById(R.id.productName);
			holder.catProductName = (TextView) convertView.findViewById(R.id.catProductName);
			holder.minSell = (TextView) convertView.findViewById(R.id.minSell);
			holder.minSellUnit = (TextView) convertView.findViewById(R.id.minSellUnit);
			holder.unitPrice = (TextView) convertView.findViewById(R.id.unitPrice);
			holder.unitPriceUnit = (TextView) convertView.findViewById(R.id.unitPriceUnit);
			holder.purchaseQuantity = (EditText) convertView.findViewById(R.id.purchaseQuantity);
			holder.btnDelete = (Button) convertView.findViewById(R.id.btn_delete_ec_cart_item);
			holder.mUnitText = (TextView) convertView.findViewById(R.id.textview_buy_unit);
			holder.itemMoneySum = (TextView) convertView.findViewById(R.id.money_item_sum);
			convertView.setTag(holder);
		} else {
			//此处不适合使用holder
			holder = (ViewHolder) convertView.getTag();
			if (newPurchaseQuantity != null) {
				newPurchaseQuantity.requestFocus();
			}
		}
		final EcCartItem item = (EcCartItem) getItem(pos);
		holder.cbSelectItem.setChecked(item.isSelected());
		holder.supplierName.setText(item.getLinkedName());
		holder.supplierAddress.setText(item.getAddress());
		if (item.getImages() != null && !item.getImages().isEmpty()) {
			DisplayImageOptions options = new DisplayImageOptions.Builder()//
					.cacheInMemory(true)//
					.cacheOnDisk(true)//
					.bitmapConfig(Config.RGB_565)//
					.build();
			ImageLoader.getInstance().displayImage(item.getImages().get(0), holder.imageEcCartItem, options);
		}
		holder.productName.setText(item.getTitle());
		holder.catProductName.setText(item.getCategory());
		holder.minSellUnit.setText(item.getUnit());
		holder.minSell.setText(StringUtil.isEmpty(item.getMinsell()) ? "0" : item.getMinsell());
		holder.unitPrice.setText(item.getUnitprice());
		holder.unitPriceUnit.setText("元/" + item.getUnit());
		
		holder.mUnitText.setText(item.getUnit());
		holder.purchaseQuantity.setTag(pos + "");
		holder.purchaseQuantity.setText(item.getPurchase_quantity());
		holder.itemMoneySum.setText(item.getMoney());
		holder.btnDelete.setTag(index);
		holder.cbSelectItem.setTag("" + index);
		
		
		//添加事件
		holder.cbSelectItem.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int position = Integer.parseInt(v.getTag().toString());
				EcCartItem item = (EcCartItem) getItem(position);
				item.setSelected(!item.isSelected());
				cartFragment.updateTotalPrice();
			}
		});
		holder.purchaseQuantity.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					touchedPosition = Integer.parseInt(v.getTag().toString());
					newPurchaseQuantity = (EditText) v;
				}
				return false;
			}
		});

		if (touchedPosition != -1 &&  touchedPosition == pos) {
			// 如果当前的行下标和点击事件中保存的index一致，手动为EditText设置焦点。
			holder.purchaseQuantity.requestFocus();
		} else {
			holder.purchaseQuantity.clearFocus();
		}
		if (newPurchaseQuantity != null) {
			newPurchaseQuantity.requestFocus();
		}
		holder.btnDelete.setOnClickListener(this);
		EditChangedListener editChangeListener = new EditChangedListener(holder.itemMoneySum, holder.purchaseQuantity);
		holder.purchaseQuantity.addTextChangedListener(editChangeListener);//TODO
		return convertView;
	}

	public class ViewHolder {
		public TextView itemMoneySum;//小计
		public TextView mUnitText;
		public CheckBox cbSelectItem;
		public TextView supplierName;
		public TextView supplierAddress;
		public ImageView imageEcCartItem;
		public TextView productName;
		public TextView catProductName;
		public TextView minSell;
		public TextView minSellUnit;
		public TextView unitPrice;
		public TextView unitPriceUnit;
		public EditText purchaseQuantity;
		public Button btnDelete;
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.btn_delete_ec_cart_item:
			deleteItem(v);
		}
	}

	/**
	 * 删除商品
	 */
	private void deleteItem(final View v) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(context);
		dialog.setTitle("删除商品");
		dialog.setMessage("确定要从购物车中删除该商品吗？");
		dialog.setCancelable(false);
		dialog.setPositiveButton("确定", new AlertDialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				progressDialog.startLoadingDialog();
				//获取当前的position
				final int currentPosition = (int) v.getTag();
				RequestService.getInstance().deleteFromEcCart(context, list.get(currentPosition).getGoods_id(), BaseEntity.class,
						new HttpRequest.RequestListener() {

							@Override
							public void onSuccess(int requestCode, BaseEntity resultData) {
								progressDialog.dismissLoadingDialog();
								if (resultData.isOk()) {
									cartFragment.requestData();
								}
							}

							@Override
							public void onFailed(int requestCode, Exception error, String msg) {
								progressDialog.dismissLoadingDialog();
								ToastUtil.toast(msg);
							}

						});
			}
		});
		dialog.setNegativeButton("取消", new AlertDialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		dialog.show();
	}

	
	private class EditChangedListener implements TextWatcher {
		private final String TAG = "CART_ITEM_EDIT_TEXT";

		private TextView itemMoneySum;// 小计
		private EditText purchaseQuantity;//采购数量文本框
		

		public EditChangedListener(TextView itemMoneySum, EditText purchaseQuantity) {
			super();
			this.itemMoneySum = itemMoneySum;
			this.purchaseQuantity = purchaseQuantity;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			LogUtil.i(TAG, "输入文本之前的状态");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			LogUtil.i(TAG, "输入文字中的状态，count是一次性输入字符数");

		}

		@Override
		public void afterTextChanged(Editable s) {
			LogUtil.i(TAG, "输入文字后的状态");
			String buyQuantity = s.toString();
			double buyQuantityDouble = 0;
			//判断是否是是数字，如果不是，恢复到录入前的数字
			try {
				buyQuantityDouble = NumberUtil.parseMoneyNumber(buyQuantity);
			} catch (ParseException e) {
				LogUtil.e(TAG, "录入的采购数量不符合数字格式，当前数字为：" + buyQuantity);
//				ToastUtil.toast("采购数量格式错误");
				itemMoneySum.setText("0");
				return;
			}
			int position = Integer.parseInt(purchaseQuantity.getTag().toString());
			EcCartItem item = (EcCartItem) getItem(position);
			item.setPurchase_quantity(buyQuantity);
			updateItemMoneySum(buyQuantityDouble);

		}
		
		/**
		 * 更新小计金额
		 */
		private void updateItemMoneySum(double buyQuantity) {
			int position = Integer.parseInt(purchaseQuantity.getTag().toString());
			EcCartItem item = (EcCartItem) getItem(position);
			//更新小计金额
			String itemMoney = "" + buyQuantity * Double.parseDouble(item.getUnitprice());
			itemMoneySum.setText(itemMoney);
			item.setMoney(itemMoney);
			//更新总金额
			cartFragment.updateTotalPrice();
		}
	};
}
